/**
 * Created by John on 2016/7/15.
 */
var MongoClient = require('mongodb').MongoClient;
var mongo = new MongoClient();
var myDB = null;

mongo.connect('mongodb://localhost/', function (err, db) {
    myDB = db.db('BeginningMongoDB');
    myDB.collection('word_stats', function (err, collection) {
        console.log('Before Save:');
        showDocs(collection, saveBlueDoc);
    });
});

function showDocs(collection, callback) {
    var query = {word: 'ocean'};
    collection.find(query, function (err, items) {
        items.toArray(function (err, items) {
            for (var i = 0; i < items.length; i++) {
                console.log(items[i]);
            }
            callback(collection);
        });
    });
}

function saveBlueDoc(collection) {
    var ocean = {
        word: 'ocean',
        first: 'o',
        last: 'n',
        size: 5,
        letters: ['o', 'c', 'e', 'a', 'n'],
        stats: {
            vowels: 3,
            consonants: 2
        },
        charsets: [
            {type: "consonants", chars: ['c', 'n']},
            {type: "vowels", chars: ['o', 'e', 'a']}
        ],
        category: 'blue'
    };

    var options = {w: 1, wtimeout: 5 * 1000, journal: true, fsync: false};

    collection.save(ocean, options, function (err, items) {
        console.log();
        console.log('Save Docs Result:');
        console.log(items ? items.result : items);
        console.log();
        console.log('After Saving Doc:');
        showDocs(collection, resetDoc);
    });
}

function resetDoc(collection) {
    var query = {word: 'ocean'};
    collection.findOne(query, function (err, item) {
        delete  item.category;
        var options = {w: 1, wtimeout: 5 * 1000, journal: true, fsync: false};

        collection.save(item, options, function (err, items) {
            console.log();
            console.log('Rest Docs Result:');
            console.log(items ? items.result : items);
            console.log();
            console.log('After Resetting Doc:');
            showDocs(collection, close);
        });
    });
}

function close() {
    setTimeout(function () {
        myDB.close();
    }, 3000);
}